const apiPath = '/api/config/'

async function getConfig() {
	try {
		const response = await $.ajax({
			url: apiPath + 'get',
			type: 'GET',
		})

		const { code, msg, data } = response

		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		const { domain, adminKey } = data

		const http = location.protocol === 'https:' ? 'https' : 'http'
		const url = `${http}://${domain}/admin/login.html${adminKey ? `?adminKey=${adminKey}` : ''}`
		
		$('#textAddress').text(url).prop('href', `./login.html${adminKey ? `?adminKey=${adminKey}` : ''}`)

		for (let key in data) {
			if (data.hasOwnProperty(key)) {
				const $input = $(`input[name="${key}"]`)
					, $textarea = $(`textarea[name="${key}"]`)
					, $select = $(`select[name="${key}"]`)
					, val = data[key]

				if ($input.length > 0) {
					$input.val(val)
				}

				else if ($textarea.length > 0) {
					$textarea.val(val)
				}
				
				else if ($select.length > 0) {
					$select.selectpicker()

					const $option = $select.find('option')

					$select.selectpicker('val', val)

					$option.each(function (_index, item) {
						if ($(item).val() === val) {
							$(item).attr('selected', 'selected')
						}
					})
				}
				
				else {
					console.warn('暂无匹配')
					continue
				}
			} else {
				console.warn('暂无匹配')
			}
		}
		
		// 行为验证监听器
		const captchaId = data.captchaId
		const captchaKey = data.captchaKey

		const $testBehaviorVerification = $('#testBehaviorVerification')
		
		if (captchaId && captchaKey) {
			$testBehaviorVerification.parent().addClass('d-grid')
			
			$('.lazyload').lazyload({
				root: null,
				rootMargin: '100px',
				threshold: 0
			})

			await initGeetest4({
				captchaId,
				product: 'bind',
				language: 'zho'
			}, gt => {
				const showCaptcha = () => gt.showCaptcha()

				$testBehaviorVerification.off('click')
				$testBehaviorVerification.on('click', showCaptcha)

				gt.onSuccess(async () => {
					try {
						const result = await gt.getValidate()
						$.get(`${apiPath}testBehaviorVerification`, result, data => {
							const { code, msg } = data 
							if (code !== 200) {
								showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
								return
							}

							showNotify(msg, 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'right')
						})
					} catch (error) {
						showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
					}
				})

				gt.onError(error => {
					console.error('行为验证有误: ', error)
					showNotify(`行为验证有误（ID: ${captchaId}），请重新提交`, 'danger', 5000, 'mdi mdi-alert', 'top', 'right');
				})
			})
		} else {
			$testBehaviorVerification.parent().removeClass('d-grid')
		}
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('服务器有误: ', error)
	}
}

$(document).ready(async (e) => {
	$('input, textarea').attr('autocomplete', 'off')

	await getConfig()

	$('#configForm').on('submit', async function (e) {
		e.preventDefault()
		const formArrayInfo = $(this).serializeArray()
		let obj = {}
		$.each(formArrayInfo, function (_index, item) {
			obj[item.name] = item.value || ''
		})

		const jsonStr = JSON.stringify(obj)
		try {
			const response = await $.ajax({
				url: apiPath + 'set',
				type: 'POST',
				data: jsonStr,
				contentType: 'application/json',
			})

			const { code, msg } = response
			
			if (code !== 200) {
				showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
				return
			}

			showNotify(msg, 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'right')
			getConfig()
		} catch (error) {
			showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			console.error('服务器有误: ', error)
		}
	})
})